package com.aote.expression.unit;

import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.browsesoft.PropertiesService;

/**
 * 单位处理器工厂，根据单位名称找对应的单位处理器，进行数据转换
 */
public class UnitProcessorFactory {
	/**
	 * 缓存的单位处理器
	 */
	private Map unitProcessors;

	/**
	 * 单列
	 */
	private static UnitProcessorFactory self = new UnitProcessorFactory();

	public static UnitProcessorFactory getInstance() {
		return self;
	}

	private UnitProcessorFactory() {
		this.unitProcessors = load();
	}

	/**
	 * 根据属性文件配置，加载函数
	 */
	private Map load() {
		Map result = new HashMap();
		NodeList nl = PropertiesService.getDocument().getElementsByTagName(
				"unitprocessor");
		for (int i = 0; i < nl.getLength(); i++) {
			Element e = (Element) nl.item(i);
			// 得到函数名，类名，根据类名构造对象
			String name = e.getAttribute("name");
			String cname = e.getAttribute("class");
			try {
				UnitProcessor up = (UnitProcessor) Class.forName(cname)
						.newInstance();
				result.put(name, up);
			} catch (InstantiationException e1) {
				throw new RuntimeException("类不可以实例化：" + cname);
			} catch (IllegalAccessException e1) {
				throw new RuntimeException("类不可以访问：" + cname);
			} catch (ClassNotFoundException e1) {
				throw new RuntimeException("类找不到：" + cname);
			}
		}
		return result;
	}

	/**
	 * 执行函数，函数名对应的类要在属性文件里配置
	 */
	public double process(String name, double number) {
		// 得到函数，让函数执行
		UnitProcessor up = (UnitProcessor) this.unitProcessors.get(name);
		double result = up.process(number); 
		return result;
	}
}
